/*
 * @Author: 邵东亮 1762111402@qq.com
 * @Date: 2024-12-14 15:55:34
 * @LastEditors: 邵东亮 1762111402@qq.com
 * @LastEditTime: 2024-12-16 11:12:27
 * @Description:
 * @FilePath: \express\bigData_server\routes\index.js
 */
const express = require("express");
const router = express.Router();
//注入验证模块
const jwtAuth = require("../util/user-jwt");
router.use(jwtAuth);
const userRouter = require("./user");
const loginRouter = require("./login");
const articleRouter = require("./article");
router.use("/api", userRouter); // 注入用户路由模块
router.use("/api", loginRouter); // 注入登录路由模块
router.use("/api", articleRouter); // 注入文章路由模块
// 自定义统一异常处理中间件，需要放在代码最后
router.use((err, req, res, next) => {
  console.log("authorization:", req.headers.authorization);

  // 自定义用户认证失败的错误返回
  if (err && err.name === "UnauthorizedError") {
    const { status = 401, message } = err;
    // 抛出401异常
    res.status(status).json({
      code: status,
      msg: "token失效，请重新登录",
      data: null,
    });
  } else {
    const { output } = err || {};
    // 错误码和错误信息
    const errCode = (output && output.statusCode) || 500;
    const errMsg =
      (output && output.payload && output.payload.error) || err.message;
    res.status(errCode).json({
      code: errCode,
      msg: errMsg,
    });
  }
});
module.exports = router;
